package com.szly.phm.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szly.phm.common.entity.dto.stu.*;
import com.szly.phm.common.entity.dto.user.LoginUserDTO;
import com.szly.phm.common.entity.po.*;
import com.szly.phm.common.entity.result.CodeStatusEnum;
import com.szly.phm.common.entity.result.PageResult;
import com.szly.phm.common.entity.result.RootResponse;
import com.szly.phm.common.entity.vo.sc.ClassByMajorIdDTO;
import com.szly.phm.common.entity.vo.sc.ScTeachDataVO;
import com.szly.phm.common.mapper.*;
import com.szly.phm.common.service.IScService;
import com.szly.phm.common.utils.BeanCopyUtils;
import com.szly.phm.common.utils.HandleUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-07-02
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysScServiceImpl   implements IScService {

    private final ScClassMapper scClassMapper;

    private final ScMajorMapper scMajorMapper;

    private final ScStudentMapper scStudentMapper;

    private final  ScTeachDataMapper scTeachDataMapper;

    private final  ScTeachDataTypeMapper scTeachDataTypeMapper;

    private final SysUserMapper sysUserMapper;
    @Override
    public RootResponse createClass(CreateClassDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScClass>();
        wrapper.eq(ScClass::getIsSoftDelete, false);
        wrapper.and(wrapper1 -> wrapper1.eq(ScClass::getClassId, roleDTO.getClassId()).or().eq(ScClass::getClassName, roleDTO.getClassName()));
        if(scClassMapper.selectOne(wrapper)!=null){
            return RootResponse.error("班级编号或名称已存在！！！");
        }
        var scClass=new ScClass();
        BeanCopyUtils.copy(roleDTO,scClass);
        scClass.setId(HandleUtils.UUID32());
        scClass.setCreator(userDTO.getUsername());
        scClass.setCreateDateTime(new Date());
        scClass.setIsSoftDelete(false);
        int i =  scClassMapper.insert(scClass);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse createMajor(CreateMajorDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScMajor>();
        wrapper.eq(ScMajor::getIsSoftDelete, false);
//        wrapper.eq(ScMajor::getMajorId,roleDTO.getMajorId());
        wrapper.and(wrapper1 -> wrapper1.eq(ScMajor::getMajorId, roleDTO.getMajorId()).or().eq(ScMajor::getMajorName, roleDTO.getMajorName()));
        if(scMajorMapper.selectOne(wrapper)!=null){
            return RootResponse.error("专业编号或名称已存在！！！");
        }
        var scMajor=new ScMajor();
        BeanCopyUtils.copy(roleDTO,scMajor);
        scMajor.setId(HandleUtils.UUID32());
        scMajor.setCreator(userDTO.getUsername());
        scMajor.setCreateDateTime(new Date());
        scMajor.setIsSoftDelete(false);
        int i =  scMajorMapper.insert(scMajor);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse createStudent(CreateStudentDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScStudent>();
        wrapper.eq(ScStudent::getIsSoftDelete, false);
        wrapper.eq(ScStudent::getStudentId,roleDTO.getStudentId());
        if(scStudentMapper.selectOne(wrapper)!=null){
            return RootResponse.error("学号已存在！！！");
        }
        var scStudent=new ScStudent();
        scStudent.setStudentId(roleDTO.getStudentId());
        scStudent.setClassId(roleDTO.getClassId());
        scStudent.setName(roleDTO.getName());
        scStudent.setRemarks(roleDTO.getRemarks());
        scStudent.setId(HandleUtils.UUID32());
        scStudent.setCreator(userDTO.getUsername());
        scStudent.setCreateDateTime(new Date());
        scStudent.setIsSoftDelete(false);
        int i =  scStudentMapper.insert(scStudent);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse createTeachData(CreateTeachDataDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScTeachData>();
        wrapper.eq(ScTeachData::getIsSoftDelete, false);
        wrapper.eq(ScTeachData::getName,roleDTO.getName());
        wrapper.eq(ScTeachData::getDataTypeId,roleDTO.getDataTypeId());
        if(scTeachDataMapper.selectOne(wrapper)!=null){
            return RootResponse.error("名称已存在！！！");
        }
        var scTeachData=new ScTeachData();
        BeanCopyUtils.copy(roleDTO,scTeachData);
        scTeachData.setId(HandleUtils.UUID32());
        scTeachData.setCreator(userDTO.getUsername());
        scTeachData.setCreateDateTime(new Date());
        scTeachData.setIsSoftDelete(false);
        int i =  scTeachDataMapper.insert(scTeachData);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse createTeachDataType(CreateTeachDataTypeDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScTeachDataType>();
        wrapper.eq(ScTeachDataType::getIsSoftDelete, false);
        wrapper.eq(ScTeachDataType::getName,roleDTO.getName());
        if(scTeachDataTypeMapper.selectOne(wrapper)!=null){
            return RootResponse.error("名称已存在！！！");
        }
        var teachDataType=new ScTeachDataType();
        BeanCopyUtils.copy(roleDTO,teachDataType);
        teachDataType.setId(HandleUtils.UUID32());
        teachDataType.setCreator(userDTO.getUsername());
        teachDataType.setCreateDateTime(new Date());
        teachDataType.setIsSoftDelete(false);
        int i =  scTeachDataTypeMapper.insert(teachDataType);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateClass(UpdateClassDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScClass>();
        wrapper.eq(ScClass::getIsSoftDelete, false);
        wrapper.and(wrapper1 -> wrapper1.eq(ScClass::getClassId, roleDTO.getMajorId()).or().eq(ScClass::getClassName, roleDTO.getClassName()));
        var scClassList=scClassMapper.selectList(wrapper);
        if(scClassList.size()>1){
            return RootResponse.error("班级名称或编号已存在！！！");
        }
        if(scClassList.size()==1&&!roleDTO.getId().equals(scClassList.get(0).getId())){
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(),"班级名称或编号已存在！！！");
        }
        var scClass=new ScClass();
        BeanCopyUtils.copy(roleDTO,scClass);
        int i =scClassMapper.updateById(scClass);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateMajor(UpdateMajorDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScMajor>();
        wrapper.eq(ScMajor::getIsSoftDelete, false);
        wrapper.and(wrapper1 -> wrapper1.eq(ScMajor::getMajorId, roleDTO.getMajorId()).or().eq(ScMajor::getMajorName, roleDTO.getMajorName()));
        var scClassList=scMajorMapper.selectList(wrapper);
        if(scClassList.size()>1){
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(),"专业名称或编号已存在！！！");
        }
        if(scClassList.size()==1&&!roleDTO.getId().equals(scClassList.get(0).getId())){
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(),"专业名称或编号已存在！！！");
        }
        var scMajor=new ScMajor();
        BeanCopyUtils.copy(roleDTO,scMajor);
        int i =scMajorMapper.updateById(scMajor);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateStudent(UpdateStudentDTO roleDTO, LoginUserDTO userDTO) {
        var scStudent=new ScStudent();
        BeanCopyUtils.copy(roleDTO,scStudent);
        int i =scStudentMapper.updateById(scStudent);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateTeachData(UpdateTeachDataDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScTeachData>();
        wrapper.eq(ScTeachData::getIsSoftDelete, false);
        wrapper.eq(ScTeachData::getName,roleDTO.getName());
        wrapper.eq(ScTeachData::getDataTypeId,roleDTO.getDataTypeId());
        var teachDatas=scTeachDataMapper.selectList(wrapper);
        if(teachDatas!=null&&teachDatas.size()!=0&&!teachDatas.get(0).getId().equals(roleDTO.getId())){
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(),"名称已存在！！！");
        }
        var scTeachData=new ScTeachData();
        BeanCopyUtils.copy(roleDTO,scTeachData);
        int i =scTeachDataMapper.updateById(scTeachData);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse updateTeachDataType(UpdateTeachDataTypeDTO roleDTO, LoginUserDTO userDTO) {
        var wrapper = new LambdaQueryWrapper<ScTeachDataType>();
        wrapper.eq(ScTeachDataType::getIsSoftDelete, false);
        wrapper.eq(ScTeachDataType::getName,roleDTO.getName());
        var teachDatas=scTeachDataTypeMapper.selectList(wrapper);

        if(teachDatas.size()!=0&&teachDatas.size()!=0&&!teachDatas.get(0).getId().equals(roleDTO.getId())){
            return RootResponse.error(CodeStatusEnum.EXIST_USERNAME.getCode(),"名称已存在！！！");
        }
        var scTeachDataType=new ScTeachDataType();
        BeanCopyUtils.copy(roleDTO,scTeachDataType);
        int i =scTeachDataTypeMapper.updateById(scTeachDataType);
        return i == 1 ? RootResponse.success() : RootResponse.error();
    }

    @Override
    public RootResponse deleteClass(String id, LoginUserDTO userDTO) {

        var queryWrapper = new LambdaQueryWrapper<ScClass>();
        queryWrapper.eq(ScClass::getId, id);
        queryWrapper.eq(ScClass::getIsSoftDelete, false);
        var scClass = scClassMapper.selectOne(queryWrapper);
        if (scClass == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        var queryWrapper1 = new LambdaQueryWrapper<ScStudent>();
        queryWrapper1.eq(ScStudent::getClassId, scClass.getId());
        queryWrapper1.eq(ScStudent::getIsSoftDelete, false);
        var scStudents=scStudentMapper.selectList(queryWrapper1);
        if(!scStudents.isEmpty()){
            return RootResponse.error("请先删除此班级的学生！！！");
        }
        scClass.setUpdater(userDTO.getUsername());
        scClass.setUpdateDateTime(new Date());
        scClass.setIsSoftDelete(true);
        int i = scClassMapper.updateById(scClass);
        if (i != 1) {
            return RootResponse.error();
        }
        return RootResponse.success(scClass);
    }

    @Override
    public RootResponse deleteMajor(String id, LoginUserDTO userDTO) {
        var queryWrapper = new LambdaQueryWrapper<ScMajor>();
        queryWrapper.eq(ScMajor::getId, id);
        queryWrapper.eq(ScMajor::getIsSoftDelete, false);
        var scClass = scMajorMapper.selectOne(queryWrapper);
        if (scClass == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        else {
            var queryWrapper1 = new LambdaQueryWrapper<ScClass>();
            queryWrapper1.eq(ScClass::getMajorId, scClass.getId());
            queryWrapper1.eq(ScClass::getIsSoftDelete, false);
            var scStudents=scClassMapper.selectList(queryWrapper1);
            if(!scStudents.isEmpty()){
                return RootResponse.error("请先删除此专业的班级！！！");
            }
        }
        scClass.setUpdater(userDTO.getUsername());
        scClass.setUpdateDateTime(new Date());
        scClass.setIsSoftDelete(true);
        int i = scMajorMapper.updateById(scClass);
        if (i != 1) {
            return RootResponse.error();
        }
        return RootResponse.success(scClass);
    }

    @Override
    public RootResponse deleteStudent(String id, LoginUserDTO userDTO) {


        var queryWrapper = new LambdaQueryWrapper<ScStudent>();
        queryWrapper.eq(ScStudent::getId, id);
        queryWrapper.eq(ScStudent::getIsSoftDelete, false);
        var scClass = scStudentMapper.selectOne(queryWrapper);
        if (scClass == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        //删除用户
        var queryWrapper1 = new LambdaQueryWrapper<SysUser>();
        queryWrapper1.eq(SysUser::getUsername, scClass.getStudentId());
        SysUser sysUser=new SysUser();
        sysUser.setIsSoftDelete(true);
        sysUserMapper.update(sysUser,queryWrapper1);
        //删除学生
        scClass.setUpdater(userDTO.getUsername());
        scClass.setUpdateDateTime(new Date());
        scClass.setIsSoftDelete(true);
        int i = scStudentMapper.updateById(scClass);
        if (i != 1) {
            return RootResponse.error();
        }
        return RootResponse.success();
    }

    @Override
    public RootResponse deleteTeachData(String id, LoginUserDTO userDTO) {
        var queryWrapper = new LambdaQueryWrapper<ScTeachData>();
        queryWrapper.eq(ScTeachData::getId, id);
        queryWrapper.eq(ScTeachData::getIsSoftDelete, false);
        var scClass = scTeachDataMapper.selectOne(queryWrapper);
        if (scClass == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }
        scClass.setUpdater(userDTO.getUsername());
        scClass.setUpdateDateTime(new Date());
        scClass.setIsSoftDelete(true);
        int i = scTeachDataMapper.updateById(scClass);
        if (i != 1) {
            return RootResponse.error();
        }
        return RootResponse.success();
    }

    @Override
    public RootResponse deleteTeachDataType(String id, LoginUserDTO userDTO) {
        var queryWrapper = new LambdaQueryWrapper<ScTeachDataType>();
        queryWrapper.eq(ScTeachDataType::getId, id);
        queryWrapper.eq(ScTeachDataType::getIsSoftDelete, false);
        var scClass = scTeachDataTypeMapper.selectOne(queryWrapper);
        if (scClass == null) {
            return RootResponse.error(CodeStatusEnum.NOT_EXIST_DATA);
        }else {
            var queryWrapper1 = new LambdaQueryWrapper<ScTeachData>();
            queryWrapper1.eq(ScTeachData::getDataTypeId, scClass.getId());
            queryWrapper1.eq(ScTeachData::getIsSoftDelete, false);
            var scStudents=scTeachDataMapper.selectList(queryWrapper1);
            if(!scStudents.isEmpty()){
                return RootResponse.error("请先删除教学资料！！！");
            }
        }
        scClass.setUpdater(userDTO.getUsername());
        scClass.setUpdateDateTime(new Date());
        scClass.setIsSoftDelete(true);
        int i = scTeachDataTypeMapper.updateById(scClass);
        if (i != 1) {
            return RootResponse.error();
        }
        return RootResponse.success(scClass);
    }

    @Override
    public RootResponse selectStudent(StudentPageDTO studentPageDTO) {
        PageHelper.startPage(studentPageDTO.getPageNum(), studentPageDTO.getPageSize());
      var studentInfoVOS=  scStudentMapper.selectStudentInfo(studentPageDTO);
        var pageInfo = PageInfo.of(studentInfoVOS);
//        scStudentMapper.selectJoinList(StudentInfoVO.class,
//                new MPJQueryWrapper<>()
//                        .select("addr.tel", "addr.address", "a.province")
//                        .leftJoin("sc_class class on t.id = addr.user_id")
//                        .rightJoin("area a on addr.area_id = a.id")
//                        .gt(true, UserDO::getId, 1)
//                        .eq(true, UserDO::getSex, "男")
//                        .stringQuery()
//                        .like(true, "addr.tel", "1")
//                        .le(true, "a.province", "1"));
        return RootResponse.success(PageResult.page(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));
    }

    @Override
    public RootResponse selectAllMajor( MajorPageDTO majorPageDTO) {
        PageHelper.startPage(majorPageDTO.getPageNum(), majorPageDTO.getPageSize());
        var queryWrapper = new LambdaQueryWrapper<ScMajor>();
        queryWrapper.eq(ScMajor::getIsSoftDelete, false);
        queryWrapper.orderByDesc(ScMajor::getCreateDateTime);
        if(majorPageDTO.getName()!=null){
            queryWrapper.like(ScMajor::getMajorName, majorPageDTO.getName());
        }
       var majors= scMajorMapper.selectList(queryWrapper);
        var pageInfo = PageInfo.of(majors);

        return RootResponse.success(PageResult.page(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));

    }

    @Override
    public RootResponse selectClassByMajorId(ClassPageDTO classPageDTO) {
        PageHelper.startPage(classPageDTO.getPageNum(), classPageDTO.getPageSize());
        var queryWrapper = new LambdaQueryWrapper<ScClass>();
        queryWrapper.eq(ScClass::getIsSoftDelete, false);
        if(classPageDTO.getMajorId()!=null){
            queryWrapper.eq(ScClass::getMajorId, classPageDTO.getMajorId());
        }
        if(classPageDTO.getName()!=null){
            queryWrapper.like(ScClass::getClassName, classPageDTO.getName());
        }
        var classes= scClassMapper.selectList(queryWrapper);
        var pageInfo = PageInfo.of(classes);
        var newList= new ArrayList<ClassByMajorIdDTO>();
        classes.forEach(p->{
            var classByMajorIdDTO=new  ClassByMajorIdDTO();
            BeanCopyUtils.copy(p,classByMajorIdDTO);
            var queryWrapper1 = new LambdaQueryWrapper<ScMajor>();
            queryWrapper1.eq(ScMajor::getIsSoftDelete, false);
            queryWrapper1.eq(ScMajor::getId, p.getMajorId());
           var major= scMajorMapper.selectOne(queryWrapper1);
            classByMajorIdDTO.setMajorName(major==null?null:major.getMajorName());
            newList.add(classByMajorIdDTO);
        });
        return RootResponse.success(PageResult.page(newList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));

    }

    @Override
    public RootResponse selectTeachData(TeachDataPageDTO teachDataPageDTO, LoginUserDTO userDTO) {
        var newList=new ArrayList<ScTeachDataVO>();
        PageHelper.startPage(teachDataPageDTO.getPageNum(), teachDataPageDTO.getPageSize());
        var queryWrapper = new LambdaQueryWrapper<ScTeachData>();
        queryWrapper.eq(ScTeachData::getIsSoftDelete, false);
        queryWrapper.orderByDesc(ScTeachData::getCreateDateTime);
        if(teachDataPageDTO.getName()!=null){
            queryWrapper.like(ScTeachData::getName, teachDataPageDTO.getName());
        }
        if(teachDataPageDTO.getTypeId()!=null){
            queryWrapper.eq(ScTeachData::getDataTypeId, teachDataPageDTO.getTypeId());
        }
        var raserverAreas= scTeachDataMapper.selectList(queryWrapper);
        var pageInfo = PageInfo.of(raserverAreas);
     pageInfo.getList().forEach(p->{
         var scTeachDataVO= new ScTeachDataVO();
         BeanCopyUtils.copy(p,scTeachDataVO);
         scTeachDataVO.setDataTypeName(  scTeachDataTypeMapper.selectById(p.getDataTypeId()).getName());
         newList.add(scTeachDataVO);
     });
        return RootResponse.success(PageResult.page(newList, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));

    }

    @Override
    public RootResponse selectTeachDataType(TeachDataTypePageDTO teachDataTypePageDTO, LoginUserDTO userDTO) {

        PageHelper.startPage(teachDataTypePageDTO.getPageNum(), teachDataTypePageDTO.getPageSize());
        var queryWrapper = new LambdaQueryWrapper<ScTeachDataType>();
        queryWrapper.eq(ScTeachDataType::getIsSoftDelete, false);
        if(teachDataTypePageDTO.getName()!=null){
            queryWrapper.like(ScTeachDataType::getName, teachDataTypePageDTO.getName());
        }
        queryWrapper.orderByDesc(ScTeachDataType::getCreateDateTime);
        var raserverAreas= scTeachDataTypeMapper.selectList(queryWrapper);
        var pageInfo = PageInfo.of(raserverAreas);

        return RootResponse.success(PageResult.page(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal()));

    }


}
